import * as THREE from 'three';
const loader = new THREE.TextureLoader();

const Er = 1000;
const br = Math.PI / 180;
const wr = 180 / Math.PI;

export const getTexture = ({ url, ...options }, onProgress?) => {
  return new Promise((resolve, reject) => {
    loader.load(
      url,
      texture => {
        for (const key in options) {
          texture[key] = options[key];
        }
        resolve(texture);
      },
      onProgress,
      reject
    );
  });
};

export function lngLatToMercator(t, e?) {
  var i = [t, e];
  if (t instanceof Array) {
    i = t;
  } else if (t instanceof Object) {
    i = [t.lng, t.lat];
  }
  var r = (i[0] * Er) / 180;
  var o = Math.log(Math.tan(((90 + i[1]) * br) / 2)) / br;
  return { x: r, y: (o = (o * Er) / 180) };
}

export function lonlat2xyz(lonlat, R) {
  var lon = (lonlat[0] * Math.PI) / 180; //转弧度值
  var lat = (lonlat[1] * Math.PI) / 180; //转弧度值
  lon = -lon; // three.js坐标系z坐标轴对应经度-90度，而不是90度

  // 经纬度坐标转球面坐标计算公式
  var x = R * Math.cos(lat) * Math.cos(lon);
  var y = R * Math.sin(lat);
  var z = R * Math.cos(lat) * Math.sin(lon);
  // 返回球面坐标
  return { x, y, z };
}

/*
经纬度转墨卡托
@params
lonlat     转换前经纬度坐标的对象
*/
export function lonlat2mercator(lonlat, R = 20037508.34) {
  var mercator = {
    x: 0,
    y: 0
  };
  var x = (lonlat[0] * R) / 180;
  var y = Math.log(Math.tan(((90 + lonlat[1]) * Math.PI) / 360)) / (Math.PI / 180);
  y = (y * R) / 180;
  mercator.x = x;
  mercator.y = y;
  return mercator;
}

/*
墨卡托转经纬度
@params
lonlat     转换前墨卡托坐标的对象
*/
export function mercator2lonlat(mercator, R = 20037508.34) {
  var lonlat = {
    x: 0,
    y: 0
  };
  var x = (mercator.x / R) * 180;
  var y = (mercator.y / R) * 180;
  y = (180 / Math.PI) * (2 * Math.atan(Math.exp((y * Math.PI) / 180)) - Math.PI / 2);
  lonlat.x = x;
  lonlat.y = y;
  return lonlat;
}

export function converColor(color) {
  var rgba = color.match(/\d+\.?\d*/g);
  if (rgba.length === 4) {
    const [r, g, b, a] = rgba;
    return { r: Number(r), g: Number(g), b: Number(b), a: Number(a) };
  } else {
    const xx = new THREE.Color(color);
    return { r: xx.r, g: xx.g, b: xx.b, a: 1 };
  }
}
